package com.roger.homecenterscreen.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.net.Inet4Address
import java.net.NetworkInterface

/**
 * 网络状态监控服务
 * 监控WiFi连接状态、SSID、IP地址等信息
 */
class NetworkStatusService(private val context: Context) {
    
    companion object {
        private const val TAG = "NetworkStatusService"
    }
    
    private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    private val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    
    private val _networkStatus = MutableStateFlow(NetworkStatus())
    val networkStatus: StateFlow<NetworkStatus> = _networkStatus.asStateFlow()
    
    private val networkCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            Log.d(TAG, "网络连接可用")
            updateNetworkStatus()
        }
        
        override fun onLost(network: Network) {
            super.onLost(network)
            Log.d(TAG, "网络连接丢失")
            updateNetworkStatus()
        }
        
        override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities)
            Log.d(TAG, "网络能力发生变化")
            updateNetworkStatus()
        }
    }
    
    /**
     * 开始监控网络状态
     */
    fun startMonitoring() {
        Log.i(TAG, "开始监控网络状态")
        
        val networkRequest = NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .build()
        
        connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
        
        // 立即获取一次当前状态
        updateNetworkStatus()
    }
    
    /**
     * 停止监控网络状态
     */
    fun stopMonitoring() {
        Log.i(TAG, "停止监控网络状态")
        connectivityManager.unregisterNetworkCallback(networkCallback)
    }
    
    /**
     * 更新网络状态信息
     */
    private fun updateNetworkStatus() {
        try {
            val status = getCurrentNetworkStatus()
            _networkStatus.value = status
            
            Log.d(TAG, "网络状态更新: ${status.connectionType} | ${status.ssid} | ${status.ipAddress} | 连接状态: ${status.isConnected}")
            
            // 如果无网络，记录警告信息
            if (!status.isConnected) {
                Log.w(TAG, "⚠️ 网络断开：${status.connectionType}")
            }
        } catch (e: Exception) {
            Log.e(TAG, "更新网络状态失败", e)
            _networkStatus.value = NetworkStatus(
                isConnected = false,
                connectionType = "网络异常",
                ipAddress = "无法获取IP",
                ssid = "网络错误",
                errorMessage = "${e.javaClass.simpleName}: ${e.message}"
            )
        }
    }
    
    /**
     * 获取当前网络状态
     */
    private fun getCurrentNetworkStatus(): NetworkStatus {
        val activeNetwork = connectivityManager.activeNetwork
        if (activeNetwork == null) {
            Log.w(TAG, "无活动网络连接")
            return NetworkStatus(
                isConnected = false,
                connectionType = "无网络",
                ipAddress = "无IP地址",
                ssid = "无WiFi",
                errorMessage = "设备未连接到任何网络"
            )
        }
        
        val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork)
        if (networkCapabilities == null) {
            return NetworkStatus(
                isConnected = false,
                connectionType = "网络异常",
                ipAddress = "无IP地址",
                ssid = "无WiFi"
            )
        }
        
        val isConnected = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        val connectionType = when {
            networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "WiFi"
            networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "移动网络"
            networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "以太网"
            else -> "未知网络"
        }
        
        val ipAddress = getCurrentIpAddress()
        val ssid = if (connectionType == "WiFi") getCurrentWifiSSID() else "非WiFi"
        
        return NetworkStatus(
            isConnected = isConnected,
            connectionType = connectionType,
            ipAddress = ipAddress,
            ssid = ssid
        )
    }
    
    /**
     * 获取当前IP地址
     */
    private fun getCurrentIpAddress(): String {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            for (networkInterface in interfaces) {
                if (!networkInterface.isUp || networkInterface.isLoopback) continue
                
                val addresses = networkInterface.inetAddresses
                for (address in addresses) {
                    if (!address.isLoopbackAddress && address is Inet4Address) {
                        return address.hostAddress ?: "无IP地址"
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取IP地址失败", e)
        }
        return "无IP地址"
    }
    
    /**
     * 获取当前WiFi SSID
     */
    private fun getCurrentWifiSSID(): String {
        try {
            if (!wifiManager.isWifiEnabled) {
                return "WiFi未启用"
            }
            
            val wifiInfo: WifiInfo? = wifiManager.connectionInfo
            if (wifiInfo != null) {
                var ssid = wifiInfo.ssid
                if (ssid != null && ssid != "<unknown ssid>") {
                    // 移除SSID两端的引号
                    ssid = ssid.replace("\"", "")
                    return ssid
                }
            }
        } catch (e: SecurityException) {
            Log.w(TAG, "获取WiFi SSID需要权限: ${e.message}")
            return "需要权限"
        } catch (e: Exception) {
            Log.e(TAG, "获取WiFi SSID失败", e)
        }
        return "未知WiFi"
    }
    
    /**
     * 手动刷新网络状态
     */
    fun refresh() {
        updateNetworkStatus()
    }
}

/**
 * 网络状态数据类
 */
data class NetworkStatus(
    val isConnected: Boolean = false,
    val connectionType: String = "未连接",
    val ipAddress: String = "无IP地址",
    val ssid: String = "无WiFi",
    val errorMessage: String? = null
) {
    /**
     * 获取显示文本
     */
    fun getDisplayText(): String {
        return if (isConnected) {
            if (connectionType == "WiFi") {
                "$ssid | $ipAddress"
            } else {
                "$connectionType | $ipAddress"
            }
        } else {
            "网络未连接"
        }
    }
    
    /**
     * 获取连接状态图标
     */
    fun getStatusIcon(): String {
        return when {
            !isConnected -> "🔴"
            connectionType == "WiFi" -> "📶"
            connectionType == "移动网络" -> "📱"
            connectionType == "以太网" -> "🔌"
            else -> "🌐"
        }
    }
}